package com.ebelter.btlibrary.btble.ble.bluetooth.device;


import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;

import com.ebelter.btlibrary.btble.ble.model.BleDevice;
import com.ebelter.btlibrary.util.ULog;

import java.util.ArrayList;
import java.util.List;

/**
 * android5.0扫描蓝牙设备方式
 *
 * @author fenghui
 */
@SuppressLint("NewApi")
public class BtScanLollipopListener extends BlueToothServer {

    private static final String TAG = "BtScanLollipopListener";
    BluetoothLeScanner mBluetoothLeScanner = null;
    List<ScanFilter> bleScanFilters  = new ArrayList<>();;
    ScanSettings bleScanSettings = null;


    public BtScanLollipopListener(Context ctx) {
        super(ctx);
    }


    //扫描设备
    @Override
    protected void scanLeDevice(boolean enable) {
        ULog.i(TAG, "-------scanLeDevice-------enable：" + enable);
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            ULog.i(TAG, "mBluetoothAdapter.isEnabled：no enable");
            return;
        }

        if (mBluetoothLeScanner == null) {
            mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            bleScanSettings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
        }
        //重新创建过滤器,用UUID来过滤

        if(!bleScanFilters.isEmpty()){
            bleScanFilters.clear();
        }

        String deviceName = BleDevice.getInstance().getConfigure().getBleName();

        ULog.i(TAG, "-------scanLeDevice-------deviceName = " + deviceName );




        if (enable) {
            ULog.d(TAG, "begin to scan bluetooth devices，mScanning：" + mScanning + ",thread:" + Thread.currentThread().getName());
            if (!mScanning) {
                mScanning = true;
                try {
                    mBluetoothLeScanner.startScan(bleScanFilters, bleScanSettings, scanCallback);
//                    mBluetoothLeScanner.startScan(scanCallback);
                    //mBluetoothLeScanner.startScan(null, bleScanSettings, scanCallback);
                } catch (Exception e) {
                    ULog.e(TAG, "startScan error." + e.getMessage());
                }
            }
            //mBluetoothLeScanner.startScan(bleScanFilters, bleScanSettings, scanCallback);
        } else {
            ULog.d(TAG, "stop to scan bluetooth devices，mScanning：" + mScanning);
            if (mScanning) {
                mScanning = false;
                try {
                    mBluetoothLeScanner.stopScan(scanCallback);
                } catch (Exception e) {
                    ULog.e(TAG, "stopScan error." + e.getMessage());
                }
            }
        }
    }


    //蓝牙5.0扫描器
    private ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(final int callbackType, final ScanResult result) {
            super.onScanResult(callbackType, result);

            BluetoothDevice device = result.getDevice();
            ULog.i(TAG, "onScanResult. callbackType is :" + callbackType
                    + ",name:" + device.getName()
                    + ",address:" + device.getAddress()
                    + ",rssi:" + result.getRssi());

//			byte[] broadcastBytes = result.getScanRecord().getBytes();
//			StringBuilder sb = new StringBuilder();
//			for (byte b : broadcastBytes) {
//				sb.append(Integer.toHexString(b));
//				sb.append(",");
//			}
//			ULog.i(TAG, "result.getScanRecord().getBytes():" + sb.substring(0, sb.length() - 1));

            if (device.getName() == null || device.getAddress() == null) {
                return;
            }

            String name = device.getName();
            currDeviceType = BluetoothUtil.getDeviceTypeByDeviceName(name);
            ULog.i(TAG, "--------------onScanResult---------------name = " + name + ", currDeviceType = " + currDeviceType);
            if (currDeviceType > -1) {
                //只有未连接的时候才继续
                if (deviceConnectState != BluetoothProfile.STATE_DISCONNECTED) {
                    ULog.e(TAG, "deviceConnectState is：" + deviceConnectState);
                    return;
                }
                ULog.i(TAG, "found the target device!");

                //TODO 发现绑定设备
//                if (mDeviceBindFoundListener != null) {
//                    if (device.getAddress() != null && device.getAddress().equals(mDeviceBindFoundListener.mac)) {
//                        mDeviceBindFoundListener.onDeviceBindFound(device);
//                    }
//                }
                //通知发现设备
                if (mScanResultCallback != null) {
                    mScanResultCallback.onDiscovered(device);
//                    deviceDataHandler.getMsgCallBack().onDiscovered(device);
                }
            }
        }

        @Override
        public void onBatchScanResults(final List<ScanResult> results) {
            super.onBatchScanResults(results);
            ULog.i(TAG, "onBatchScanResults, results size:" + results.size());
            for (ScanResult item : results) {
                ULog.i(TAG, "result info :" + item.getDevice().getName() + ","
                        + "address:" + item.getDevice().getAddress() + ", rssi:"
                        + item.getRssi());

                currDeviceType = BluetoothUtil.getDeviceTypeByDeviceName(item.getDevice().getName());
                ULog.d(TAG, "--------------onBatchScanResults---------------name = " + item.getDevice().getName() + ", currDeviceType = " + currDeviceType);
                if (currDeviceType > -1) {
                    //只有未连接的时候才继续
                    if (deviceConnectState != BluetoothProfile.STATE_DISCONNECTED) {
                        ULog.e(TAG, "deviceConnectState is：" + deviceConnectState);
                        return;
                    }
                    ULog.i(TAG, "found target device!");
                    //通知发现设备
                    if (mScanResultCallback != null) {
                        mScanResultCallback.onDiscovered(item.getDevice());
//                        deviceDataHandler.getMsgCallBack().onDiscovered(item.getDevice());
                    }
                }
            }
        }

        @Override
        public void onScanFailed(final int errorCode) {
            super.onScanFailed(errorCode);
            ULog.e(TAG, "onScanFailed, code is : " + errorCode);

            //deviceDataHandler.getMsgCallBack().onBluetoothCrash();
            //UToast.ShowTask(mContext, "系统蓝牙开小差了，重启蓝牙恢复使用.");
            //重启蓝牙
            //restartBluetooth();
//			try {
//				Thread.sleep(500);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
            //startScanDevice();
        }
    };

//    public void setmDeviceBindFoundListener(OnDeviceBindFoundListener mDeviceBindFoundListener) {
//        this.mDeviceBindFoundListener = mDeviceBindFoundListener;
//    }
}